package com.ikangtai.shecare.personal;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.BaseActivity;
import com.ikangtai.shecare.common.baseView.TopBar;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.eventBusMsg.RegisterMsg;
import com.ikangtai.shecare.common.util.ActivityCollector;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DeviceInfo;
import com.ikangtai.shecare.common.util.FormatUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegisterActivity extends BaseActivity implements View.OnClickListener, CheckBox.OnCheckedChangeListener {

    private TopBar topBar;
    private EditText phoneNumberText;
    private EditText passwordText;
    private EditText validateText;
    private Button validateBtn;
    private Button registerBtn;
    private String mobileNum;
    private String password;
    private String macAddress;
    private DeviceInfo deviceInfo;
    private DBManager dbManager;
    private CheckBox user_agree;
    private TextView user_agreement;
    private static final int REGISTER_SUCCESS = 0;
    private static final int REGISTER_FAILURE = 1;
    private static final int REGISTER_REPETE = 2;
    private static final int GET_CODE_SUCCESS = 3;
    private static final int GET_CODE_FAILURE = 4;
    private static final int VERIFY_CODE_SUCCESS = 5;
    private static final int VERIFY_CODE_FAILURE = 6;
    private static final int PHONE_NUMBER_FORMAT_NOK = 7;
    private static final int VERIFY_CODE_NOK = 8;
    private static final int VERIFY_CODE_OVERDUE = 9;
    private int registerSimpleType;
    private String openID = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register);
        ActivityCollector.addActivity(this);
        Intent intent = getIntent();
        macAddress = intent.getStringExtra("MACAddress");
        EventBus.getDefault().register(this);
        dbManager = new DBManager(this);
        deviceInfo = new DeviceInfo(this);
        initView();
    }

    private void initView() {

        topBar = (TopBar) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new TopBar.OnTopBarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void midLeftClick() {

            }

            @Override
            public void midRightClick() {

            }

            @Override
            public void rightClick() {

            }
        });
        user_agreement = (TextView) findViewById(R.id.user_agreement);
        phoneNumberText = (EditText) findViewById(R.id.register_phone_edit);
        phoneNumberText.addTextChangedListener(textWatcher);
        passwordText = (EditText) findViewById(R.id.register_password_edit);
        validateText = (EditText) findViewById(R.id.register_validation_edit);
        validateBtn = (Button) findViewById(R.id.register_validate_btn);
        registerBtn = (Button) findViewById(R.id.register_btn);
        user_agree = (CheckBox) findViewById(R.id.user_agree);
        registerBtn.setOnClickListener(this);
        user_agreement.setOnClickListener(this);
        user_agree.setOnCheckedChangeListener(this);

        getIntentMsg();
    }

    /**
     * 接收intent传来的参数
     */
    private void getIntentMsg() {
        Intent intentMsg = getIntent();
        registerSimpleType = intentMsg.getIntExtra("registerSimpleType", 0);
        openID = intentMsg.getStringExtra("openID");
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.register_validate_btn:

                validateBtn.setBackground(getResources().getDrawable(R.drawable.register_validation_button_bg));
                validateBtn.setOnClickListener(null);
                new CountDownTimer(50000, 1000) {

                    @Override
                    public void onTick(long millisUntilFinished) {
                        validateBtn.setText(millisUntilFinished / 1000 + getString(R.string.again_get));

                    }

                    @Override
                    public void onFinish() {
                        if ((phoneNumberText.getText().toString().trim().length() == 11) && isMobileNO(phoneNumberText.getText().toString().trim())) {
                            validateBtn.setBackground(getResources().getDrawable(R.drawable.register_validation_button_bg_red));
                            validateBtn.setText(R.string.get_captcha);
                            validateBtn.setOnClickListener(RegisterActivity.this);
                        } else {
                            validateBtn.setBackground(getResources().getDrawable(R.drawable.register_validation_button_bg));
                            validateBtn.setText(R.string.get_captcha);
                            validateBtn.setOnClickListener(null);
                        }
                    }
                }.start();
                getVerifyCode();
                break;
            case R.id.register_btn:

                if (user_agree.isChecked()) {

                    AppLog.e("" + !(isMobileNO(phoneNumberText.getText().toString().trim())));
                    AppLog.e("" + (passwordText.getText().toString().trim().length() < 6));
                    if (!(isMobileNO(phoneNumberText.getText().toString().trim())) || (passwordText.getText().toString().trim().length() < 6)) {
                        Toast.makeText(RegisterActivity.this, R.string.phone_qualified, Toast.LENGTH_SHORT).show();
                    } else {
                        verifyCode(phoneNumberText.getText().toString().trim(), validateText.getText().toString().trim());
                    }
                } else {
                    Toast.makeText(this, R.string.accept_user_agreement, Toast.LENGTH_SHORT).show();
                }

                break;

            case R.id.user_agreement:
                String userAgreementTitle = getString(R.string.user_agreement_title);
                String userAgreement = getString(R.string.user_agreement);

//                String updateAlertNegativeButtonTxt = getString(R.string.updateAlertNegativeButtonTxt);

                Dialog dialog = new AlertDialog.Builder(this).setTitle(userAgreementTitle)
                        .setMessage(userAgreement)
                        .setCancelable(false)
                        .setPositiveButton(getString(R.string.sure), new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }
                        ).create();
                dialog.show();
                break;
            default:
                break;
        }

    }

    private void getVerifyCode() {

        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "veri/getCode.json";
        try {
            okHttpClient.add("phoneNumber", phoneNumberText.getText().toString().trim());
            okHttpClient.add("type", 1);

            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    RegisterMsg registerMsg = new RegisterMsg();
                    try {
                        String str = response.body().string();
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            registerMsg.setRespCode(GET_CODE_SUCCESS);

                        } else if (211 == respCode) {
                            registerMsg.setRespCode(REGISTER_REPETE);
                        } else if (212 == respCode) {
                            registerMsg.setRespCode(PHONE_NUMBER_FORMAT_NOK);
                        }
                    } catch (JSONException e) {
                        registerMsg.setRespCode(GET_CODE_FAILURE);
                        e.printStackTrace();
                    }
                    EventBus.getDefault().post(registerMsg);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void verifyCode(String phoneNum, String code) {
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "veri/verifyCode.json";
        try {
            okHttpClient.add("phoneNumber", phoneNum);
            okHttpClient.add("code", code);

            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    RegisterMsg registerMsg = new RegisterMsg();
                    try {
                        String str = response.body().string();
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            registerMsg.setRespCode(VERIFY_CODE_SUCCESS);
                        } else if (208 == respCode) {
                            registerMsg.setRespCode(VERIFY_CODE_NOK);
                        } else if (209 == respCode) {
                            registerMsg.setRespCode(VERIFY_CODE_OVERDUE);
                        }
                    } catch (JSONException e) {
                        registerMsg.setRespCode(VERIFY_CODE_FAILURE);
                        e.printStackTrace();
                    }
                    EventBus.getDefault().post(registerMsg);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private void registerAccount() {

        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "login/registerSimple.json";
        password = FormatUtil.md5(passwordText.getText().toString().trim());
        try {
            okHttpClient.add("emailOrPhone", phoneNumberText.getText().toString().trim());
            okHttpClient.add("password", password);
            okHttpClient.add("location", "");
            okHttpClient.add("registerSimpleType", registerSimpleType);
            okHttpClient.add("serviceID", openID);
            okHttpClient.add("OSType", "Android");
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    RegisterMsg registerMsg = new RegisterMsg();
                    try {
                        String str = response.body().string();
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");

                        if (App.HTTP_RESP_OK == respCode) {
                            registerMsg.setRespCode(REGISTER_SUCCESS);
                            String authToken = respJSONObj.getString("authToken");

                            App.authToken = authToken;
                            App.saveUserPreference(App.SHARED_PREF_USER_TOKEN, App.authToken);

                            dbManager.insertUserPreference(phoneNumberText.getText().toString().trim(), password);
                            dbManager.updateUserPreference(phoneNumberText.getText().toString().trim(), "openID", openID);

                            App.saveUserPreference(App.SHARED_PREF_USER_NAME, phoneNumberText.getText().toString().trim());
                            App.userName = phoneNumberText.getText().toString().trim();
                            App.userPswd = password;
                        } else if (211 == respCode) {
                            registerMsg.setRespCode(REGISTER_REPETE);
                        }
                    } catch (JSONException e) {
                        registerMsg.setRespCode(REGISTER_FAILURE);
                        e.printStackTrace();
                    }
                    EventBus.getDefault().post(registerMsg);
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    @Subcriber
    private void dealRegisterMsg(RegisterMsg registerMsg) {

        int eventBusCode = registerMsg.getRespCode();
        switch (eventBusCode) {

            case REGISTER_SUCCESS:
                Toast.makeText(getApplicationContext(), R.string.register_success, Toast.LENGTH_SHORT).show();

                if (macAddress == null || macAddress.length() <= 0) {
                    App.saveUserPreference("bindType", "register");
                    Intent intent = new Intent(RegisterActivity.this, StateActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    bindFromServer();
                }

                break;
            case REGISTER_FAILURE:
                Toast.makeText(getApplicationContext(), R.string.server_error, Toast.LENGTH_SHORT).show();
                break;
            case REGISTER_REPETE:
                Toast.makeText(getApplicationContext(), R.string.phone_used, Toast.LENGTH_SHORT).show();
                break;
            case GET_CODE_SUCCESS:
                Toast.makeText(getApplicationContext(), R.string.get_captcha_success, Toast.LENGTH_SHORT).show();
                break;
            case GET_CODE_FAILURE:
                Toast.makeText(getApplicationContext(), R.string.server_captcha_error, Toast.LENGTH_SHORT).show();
                break;
            case VERIFY_CODE_SUCCESS:
                Toast.makeText(getApplicationContext(), R.string.check_captcha_right, Toast.LENGTH_SHORT).show();
                registerAccount();
                break;
            case VERIFY_CODE_FAILURE:
                Toast.makeText(getApplicationContext(), R.string.server_captcha_check_error, Toast.LENGTH_SHORT).show();
                break;
            case PHONE_NUMBER_FORMAT_NOK:
                Toast.makeText(getApplicationContext(), R.string.phone_format_error, Toast.LENGTH_SHORT).show();
                break;
            case VERIFY_CODE_NOK:
                Toast.makeText(getApplicationContext(), R.string.captcha_error_check, Toast.LENGTH_SHORT).show();
                break;
            case VERIFY_CODE_OVERDUE:
                Toast.makeText(getApplicationContext(), R.string.captcha_out_check, Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }

    }

    private void bindFromServer() {

        long time = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = new Date(time);
        String dateStr = format.format(date1);
        OKHttpUtil okHttpClient = new OKHttpUtil(this);
        String appendUrl = "hardware/bindingThermometer.json";
        try {
            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("MACAddress", macAddress);
            okHttpClient.add("OSType", deviceInfo.getPhoneVersion());
            okHttpClient.add("location", "");
            okHttpClient.add("bindingTime", dateStr);
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    try {
                        JSONObject respJSONObj = new JSONObject(response.body().string());
                        int respCode = respJSONObj.getInt("code");
                        if (200 == respCode) {
                            AppLog.i("upload registerUserInfo onResponse success!");
                            Looper.prepare();
                            //Toast.makeText(getApplicationContext(), "绑定成功!", Toast.LENGTH_SHORT).show();
                            App.saveUserPreference("bindState", "binded");
                            dbManager.updateUserPreference(App.userName, "macAddress", macAddress);
                            App.memory_preference_macAddress = macAddress;
                            Intent intent = new Intent(RegisterActivity.this, StateActivity.class);
                            startActivity(intent);
                            finish();
                            Looper.loop();
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            bindFromServer();
                        } else {
                            AppLog.i("upload registerUserInfo onResponse respCode failed! is:" + respCode);
                            Looper.prepare();
                            //Toast.makeText(getApplicationContext(), "绑定失败!", Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }
                    } catch (JSONException e) {
                        AppLog.i("upload registerUserInfo onResponse failed!");
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    public static boolean isMobileNO(String mobiles) {

//        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Pattern p = Pattern.compile("^(1[0-9][0-9])\\d{8}$");
        Matcher m = p.matcher(mobiles);

        return m.matches();

    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (s.length() == 11) {
                mobileNum = phoneNumberText.getText().toString().trim();
                if (isMobileNO(mobileNum)) {
                    validateBtn.setBackground(getResources().getDrawable(R.drawable.register_validation_button_bg_red));
                    validateBtn.setOnClickListener(RegisterActivity.this);
                }
            } else {
                validateBtn.setBackground(getResources().getDrawable(R.drawable.register_validation_button_bg));
                validateBtn.setOnClickListener(null);
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

            if (s.length() == 11) {
                mobileNum = phoneNumberText.getText().toString().trim();
                if (isMobileNO(mobileNum)) {
                    validateBtn.setBackground(getResources().getDrawable(R.drawable.register_validation_button_bg_red));
                    validateBtn.setOnClickListener(RegisterActivity.this);
                }
            } else {
                validateBtn.setBackground(getResources().getDrawable(R.drawable.register_validation_button_bg));
                validateBtn.setOnClickListener(null);
            }

        }
    };

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }


}
